package com.gobo.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gobo.eduservice.pojo.EduSubject;
import com.gobo.eduservice.pojo.excel.SubjectUploadDemo;
import com.gobo.eduservice.service.EduSubjectService;
import com.gobo.servicebase.handler.exception.pojo.GoboException;
import com.sun.org.apache.bcel.internal.generic.NEW;

public class ExcelListener extends AnalysisEventListener<SubjectUploadDemo> {

    private EduSubjectService subjectService;

    public ExcelListener() {
    }

    public ExcelListener(EduSubjectService subjectService) {
        this.subjectService = subjectService;
    }

    @Override
    public void invoke(SubjectUploadDemo subjectUploadDemo, AnalysisContext analysisContext) {
        if (subjectUploadDemo ==null){
            throw  new GoboException(30004,"课程添加上传文件为空！");
        }
        EduSubject eduOneSubject = containsOneSubject(subjectUploadDemo.getOneSubject());
        if (eduOneSubject==null){
            eduOneSubject = new EduSubject();
            eduOneSubject.setTitle(subjectUploadDemo.getOneSubject());
            eduOneSubject.setParentId("0");
            subjectService.save(eduOneSubject);
        }
        String pid = eduOneSubject.getId();
        EduSubject twoSubject = containsTwoSubject(subjectUploadDemo.getTwoSubject(), pid);
        if (twoSubject==null){
            twoSubject = new EduSubject();
            twoSubject.setTitle(subjectUploadDemo.getTwoSubject());
            twoSubject.setParentId(pid);
            subjectService.save(twoSubject);
        }


    }

    /**
     *
     * @param name  一级分类名称
     * @return
     */
    private EduSubject containsOneSubject(String name){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id","0");
        return subjectService.getOne(wrapper);
    }
    /**
     *
     * @param name  二级分类名称
     * @return
     */
    private EduSubject containsTwoSubject(String name,String pid){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",pid);
        return subjectService.getOne(wrapper);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
